package com.wholeintech.zigbee.gw;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.wholeintech.dao.BoxInfoDao;
import com.wholeintech.dao.KnxDeviceDao;
import com.wholeintech.dao.NavigationDao;
import com.wholeintech.dao.ProjectDao;
import com.wholeintech.dao.SceneDao;
import com.wholeintech.dao.SceneDeviceDao;
import com.wholeintech.dao.ServiceInfoDao;
import com.wholeintech.dao.VoiceConfigDao;
import com.wholeintech.entity.DeviceDb;
import com.wholeintech.protocol.NCN5120;
import com.wholeintech.utils.CommonIntent;
import com.wholeintech.utils.CommonUtil;
import com.wholeintech.utils.CrashExceptionUtils;
import com.wholeintech.utils.HcpFile;
import com.wholeintech.utils.LogUtils;
import com.wholeintech.zigbee.util.DeviceDbManager;
import com.wholeintech.zigbee.util.PollTheadTemp;
import com.wholeintech.zigbee.util.SerialDataUnpack;
import com.wholeintech.zigbee.util.VoiceCmd;

import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.wholeintech.utils.CommonUtil.bytesToHexString;

/**
 * Zigbee服务
 */
public class ZigBeeService extends Service {
    private final static String TAG = "ZigBeeService";
    private final static boolean debug = true;
    public final static int DELAY_DEV_CTRL_FB_TIMEOUT = 5; // 1s=10

    public final static int DEV_CTRL_UPDATA_FLAG = 2; // 1s=10
    public final static int DEV_CTRL_TIMEOUT_FB_FLAG = 1; // 1s=10

    public final static int ZIGBEE_GW_OVER_CNT = 4; // 1s=10
    public final static int ZIGBEE_ASSOC_CHECK_120S = 6; // 1s=10
    public final static int ZIGBEE_ASSOCLIST_LEN_MAX = 32; // 1s=10
    public final static int TICK_200S_CNT = 20; // 1s=10

    public final static int SERVICE_MACHINE_DBCKECK_INIT = 0; // 1s=10
    //public final static int SERVICE_MACHINE_DBCKECK_INIT = 1; // 1s=10
    public final static int SERVICE_MACHINE_UPDATA_HCP = 2; // 1s=10    
    public final static int SERVICE_MACHINE_NORMAL = 3; // 1s=10

    public final static int SERVICE_READ_DEV_LIST_TIME_1S = 50;
    public final static int SERVICE_MSG_INIT = 2010; // 1s=10
    public final static int SERVICE_MSG_UPDATA_HCP = 2011; // 1s=10  
    public final static int SERVICE_MSG_NORMAL = 2012; // 1s=10
    public final static int SERVICE_MSG_Zigbee_Reset = 2013; // 1s=10
    public final static int SERVICE_MSG_ADD_DEV = 2014; // 1s=10
    public final static int SERVICE_MSG_WatchDog = 2015; // 1s=10
    public final static int SERVICE_MSG_TICK_READLIST = 2016; //30???��������??��zigbee������?���䨬?
    public final static int SERVICE_MSG_TICK_ZigbeeGWRun = 2017;
    public final static int SERVICE_MSG_Start_DevFb_Check = 2018;

    private ZigBeeDataProcess mZigBeeDataProcess;
    private DeviceManager mDeviceManager;
    private DeviceControl mDeviceControl;
    private Context mContext;

    private DeviceDbManager mDeviceDbManager;
    private int mZbDeviceNum = 0;
    private SerialDataUnpack serialDataUnpack;

    private int devCtlTimeOutFlag = 0;
    private int mdevFbcnt = 0;

    private int mdevFbDelay = 0;

    private int zigbeeInit = 0;
    private int mZigbeeGwTimeOut = 0;
    private int mZigbeeClearAssocCnt = 0;
    private boolean msgHandleThreadZigbeeRunFlag = false;
    private boolean isRunThread = false;

    PollTheadTemp msgHandlethread;
    int msgHandleThreadCheck = 0;
    ExecutorService singleThreadExecutorHandle;
    ExecutorService singleThreadExecutorReceive;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        serialDataUnpack = SerialDataUnpack.getSingleInstance(mContext);
        IntentFilter mFilter = new IntentFilter();

        mFilter.addAction(CommonIntent.ACTION_DEV_ADD);
        mFilter.addAction(CommonIntent.ACTION_DEV_REMOVE);
        mFilter.addAction(CommonIntent.ACTION_DEV_ONOFFLINE);
        mFilter.addAction(CommonIntent.ACTION_DEV_CLEARLIST);
        mFilter.addAction(CommonIntent.ACTION_DEV_BIND);
        mFilter.addAction(CommonIntent.ACTION_DEV_UNBIND);
        mFilter.addAction(CommonIntent.ACTION_DEV_SECURITYKEY);

        mFilter.addAction(CommonIntent.ACTION_CTL_LIGHT);
        mFilter.addAction(CommonIntent.ACTION_CTL_LIGHT_8);
        mFilter.addAction(CommonIntent.ACTION_CTL_CURTAIN);
        mFilter.addAction(CommonIntent.ACTION_CTL_SWITCH);
        mFilter.addAction(CommonIntent.ACTION_CTL_FRESHAIR);
        mFilter.addAction(CommonIntent.ACTION_CTL_FLOOR_HEATING);
        mFilter.addAction(CommonIntent.ACTION_CTL_AIRCONDITION);
        mFilter.addAction(CommonIntent.ACTION_CTL_PROJECTOR);
        mFilter.addAction(CommonIntent.ACTION_CTL_AIRCLEANER);

        mFilter.addAction(CommonIntent.ACTION_TEST_DEV_STATUS);
        mFilter.addAction(CommonIntent.ACTION_CTL_CLEAR_BUFFER);

        mFilter.addAction(CommonIntent.ACTION_SENCE_ADD);
        mFilter.addAction(CommonIntent.ACTION_SENCE_DEV_ADD);
        mFilter.addAction(CommonIntent.ACTION_HCP_RESET);

        mFilter.addAction(CommonIntent.ACTION_BOX_WIREDNET_TO_ZIGBEE);
        mFilter.addAction(CommonIntent.ACTION_DEV_MANUALCLEARZIGBEEGWASSOCLIST);//add by cx  2019/12/13

        registerReceiver(mReceiver, mFilter);
        //Zigbee数据处理
        mZigBeeDataProcess = new ZigBeeDataProcess(mRxHandler, mContext);
        //Zigbee设备控制类
        mDeviceControl = DeviceControl.getInstance(mZigBeeDataProcess);
        //设备管理操作类
        mDeviceManager = DeviceManager.getInstance(mZigBeeDataProcess, mContext);
        //设备数据库操作类
        mDeviceDbManager = DeviceDbManager.getInstance(mContext);
        //初始化服务
        sendHandleMsg(SERVICE_MSG_INIT, 3000);

        msgHandlethread = new PollTheadTemp() {

            @Override
            public void threadPoll() {
                msgHandle();
            }
        };

        msgHandlethread.startThread();
        singleThreadExecutorHandle = Executors.newSingleThreadExecutor();
        singleThreadExecutorReceive = Executors.newSingleThreadExecutor();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return Service.START_STICKY;
    }

    private final Handler mRxHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            final Message deviceMsg = new Message();
            deviceMsg.obj = msg.obj;
            deviceMsg.what = msg.what;
            singleThreadExecutorHandle.execute(new Runnable() {
                @Override
                public void run() {
                    switch (deviceMsg.what) {
                        case ZigBeeDataProcess.UNPACK_RX_DATA:
                            //处理底层模块主动上报的数据
                            if (deviceMsg.obj != null) {
                                if (mDeviceManager.DeviceFbProc((byte[]) deviceMsg.obj) == 1) {
                                    //上报的是设备在线状态
                                    startDevFbCheck();
                                    Log.e(TAG,"===上报的是设备设备在线/离线状态====");
                                }
                                byte[] buf = CommonUtil.objectToByteArray(deviceMsg.obj);
                                if (buf[CommonUtil.OBJTOBYTE_CMD_POS] == DeviceManager.UART_CMD_Version) {
                                    mZigbeeGwTimeOut = 0;
                                    Log.d(TAG, "!!!!ZigBeeGW is Running!!!! ");
                                }
                            }
                            break;
                        case SERVICE_MSG_INIT: {
                            //初始化服务
                            if (mZigBeeDataProcess.startDataProcess()) {
                                Log.e(TAG, "ZigbeeServiceInit successful!!");
                                mDeviceManager.getZkey();
                                zigbeeServiceInit();
                                mDeviceManager.version();

                                NCN5120 mNCN5120 = new NCN5120();
                                byte[] test = (mNCN5120.groupWriteFloat(0, 0, 1, (float) 27.2));
                                Log.e(TAG, "mNCN5120:" + bytesToHexString(test, test.length));

                                Log.e(TAG, "VoiceCmd Num:" + VoiceCmd.getTextWithIndex());
                                Log.e(TAG, "VoiceCmd index:" + "Name:" + VoiceCmd.getTextByIndex(77));
                                mDeviceManager.readList();
                            } else {
                                Log.e(TAG, "ZigbeeServiceInit false and Retry!!");
                                sendHandleMsg(SERVICE_MSG_INIT, 1000);
                            }

                            sendHandleMsg(SERVICE_MSG_TICK_READLIST, 1000 * SERVICE_READ_DEV_LIST_TIME_1S);
                            sendHandleMsg(SERVICE_MSG_WatchDog, 1000);
                        }
                        break;
                        case SERVICE_MSG_UPDATA_HCP: {
                            //更新HCP
                            Log.e(TAG, "!!HCP reset!!");
                            int devHcpValue = (int)deviceMsg.obj;
                            HcpFile hcp = new HcpFile();
                            hcp.parser(devHcpValue);
                            updateHcp(hcp);
                            msgRemove(SERVICE_MSG_Zigbee_Reset);
                            sendHandleMsg(SERVICE_MSG_ADD_DEV, 500);
                            Log.d(TAG, "devHcpValue:" + devHcpValue);
                        }
                        break;
                        case SERVICE_MSG_Zigbee_Reset:
                            //Zigbee复位
                            Log.e(TAG, "!!SERVICE_MSG_Zigbee_Reset reset!!");
                            mDeviceManager.reset();
                            break;
                        case SERVICE_MSG_ADD_DEV: {
                            //添加设备
                            try {
                                Thread.sleep(50);
                                mDeviceManager.clearList();
                                Thread.sleep(1000);

                                mDeviceManager.ManualResetAssoclist();
                                Thread.sleep(1000);
                                mDeviceManager.reset();
                                Thread.sleep(1000);
                                mDeviceManager.DbCheck();
                                startDevFbCheck();
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                        break;
                        case SERVICE_MSG_NORMAL:
                            break;
                        case SERVICE_MSG_TICK_READLIST: {
                            if (zigbeeInit == 0)
                                break;
                            int test = 0;

                            /* read the status of zigbee device */
                            mDeviceManager.DbCheckStatus(0);
                            msgHandleThreadCheck++;

                            if (msgHandleThreadCheck >= 3 || test > 3) {
                                Log.e(TAG, "SERVICE_MSG_TICK_READLIST" + " " + msgHandleThreadCheck + " " + test);
                                msgHandleThreadCheck = 0;
                                zigbeeInit = 0;
                                //by levin
                                CrashExceptionUtils.getInstance().forceRestart(mContext);
                            } else {
                                sendHandleMsg(SERVICE_MSG_TICK_READLIST, 1000 * SERVICE_READ_DEV_LIST_TIME_1S);
                            }
                            Log.e(TAG, "!!SERVICE_MSG_TICK_READLIST!!");
                        }
                        break;
                        case SERVICE_MSG_TICK_ZigbeeGWRun: {
                            if (msgHandleThreadZigbeeRunFlag == true) {
                                mZigbeeGwTimeOut++;
                                mZigbeeClearAssocCnt++;
                                if (mZigbeeClearAssocCnt > ZIGBEE_ASSOC_CHECK_120S) {
                                    mDeviceManager.getMyDevOnlineNum();
                                    mDeviceManager.getAssoclistNum();
                                    mZigbeeClearAssocCnt = 0;
                                    Log.e(TAG, "!!getBoxZigBeeDevAssocNum=" + DeviceManager.getBoxZigBeeDevAssocNum()
                                            + "!!getBoxZigBeeDevOnlineNum=" + DeviceManager.getBoxZigBeeDevOnlineNum());
                                    if (DeviceManager.getBoxZigBeeDevAssocNum() > DeviceManager.getBoxZigBeeDevOnlineNum()
                                            && (DeviceManager.getBoxZigBeeDevAssocNum() > (ZIGBEE_ASSOCLIST_LEN_MAX - 1))) {
                                        mDeviceManager.ManualZigBeeGwClearAssoclist();
                                    }
                                }
                                mDeviceManager.version();
                                Log.e(TAG, "!!msgHandleThreadZigbeeRunCnt=" + mZigbeeGwTimeOut +
                                        "  mZigbeeClearAssocCnt=" + mZigbeeClearAssocCnt);
                                if (mZigbeeGwTimeOut == ZIGBEE_GW_OVER_CNT) {
                                    CommonUtil.ZigBeeGWShutDown();
                                    Log.e(TAG, "!!Close Zigbee Power!!");

                                }
                                if (mZigbeeGwTimeOut > ZIGBEE_GW_OVER_CNT) {
                                    if (CommonUtil.getZigBeeGWPowerIOStatus() == 0) {
                                        CommonUtil.ZigBeeGWWakeUp();
                                        Log.e(TAG, "!!Reset Zigbee Power!!");
                                        mZigbeeGwTimeOut = 0;
                                        msgHandleThreadZigbeeRunFlag = false;
                                        return;
                                    }
                                }
                                Log.e(TAG, "!!SERVICE_MSG_TICK_ZigbeeGWRun!!");
                                sendHandleMsg(SERVICE_MSG_TICK_ZigbeeGWRun, 1000 * 20);
                            }
                        }
                        break;
                        default: {
                        }
                        break;
                    }
                }
            });
        }
    };

    private void sendHandleMsg(int what, byte[] data) {
        Message mNewUnpackMsg = new Message();
        mNewUnpackMsg.what = what;
        mNewUnpackMsg.obj = data;
        mRxHandler.sendMessage(mNewUnpackMsg);
    }

    /**
     * 发送Handler消息
     * @param what
     * @param delayMs
     */
    private void sendHandleMsg(int what, int delayMs) {
        mRxHandler.removeMessages(what);
        Message mNewUnpackMsg = new Message();
        mNewUnpackMsg.what = what;
        mRxHandler.sendMessageDelayed(mNewUnpackMsg, delayMs);
    }

    private void sendHandleMsg(int what, int value, int delayMs) {
        mRxHandler.removeMessages(what);
        Message mNewUnpackMsg = new Message();
        mNewUnpackMsg.what = what;
        mNewUnpackMsg.obj = value;
        mRxHandler.sendMessageDelayed(mNewUnpackMsg, delayMs);
    }

    private void msgRemove(int what) {
        mRxHandler.removeMessages(what);
    }

    private void zigbeeServiceInit() {
        Log.d(TAG, "ZigBee Service Start");
        mZbDeviceNum = mDeviceManager.devStatusRecovery();
        zigbeeInit = SERVICE_MACHINE_NORMAL;
        startDevFbCheck();
        Log.d(TAG, "ZigBee Service Start Check Db " + "mZbDeviceNum=" + mZbDeviceNum);
    }

    //代码抛异常测试
    boolean enableRestartTest = false;
    int a = 0;

    private void msgHandle() {
        if (enableRestartTest) {
            a++;
            if (a > 100)
                CrashExceptionUtils.getInstance().forceRestart(mContext);
        }

        try {
            msgHandleThreadCheck = 0;
            mdevFbcnt++;
            if ((mdevFbcnt % 20) == 0)
                LogUtils.e(TAG, "recv msgHandle run");
            /**
             * 增加逻辑
             * 每当有新指令过来，人为延迟1秒，然后重置开始检测标记devCtlTimeOutFlag,让其能够开始检测
             */
            while (serialDataUnpack.needCheckTimeOut) {
                serialDataUnpack.needCheckTimeOut = false;
                Thread.sleep(500);
                //延迟1000ms启动检测
                devCtlTimeOutFlag = 1;
                mdevFbcnt = 0;
                mdevFbDelay = 0;
            }
            if (getDevFbCheck() == 1) {
                if (mdevFbcnt == (DELAY_DEV_CTRL_FB_TIMEOUT + mdevFbDelay * 1)) {
                    mdevFbDelay++;
                    if (mDeviceManager.DevFbCtlTimeout(mDeviceControl) == 0) {
                        mdevFbDelay = 0;
                        stopDevFbCheck();
                        sendHandleMsg(SERVICE_MSG_TICK_READLIST, 1000 * SERVICE_READ_DEV_LIST_TIME_1S);
                    }
                    mdevFbcnt = 0;
                }
            } else {
                if ((mdevFbcnt % 20) == 0) {
                    if (!msgHandleThreadZigbeeRunFlag) {
                        mDeviceManager.version();
                        sendHandleMsg(SERVICE_MSG_TICK_ZigbeeGWRun, 1000 * 20);
                        msgHandleThreadZigbeeRunFlag = true;
                    }
                }
            }
            Thread.sleep(200);
        } catch (Exception e) {
            Log.e(TAG, "write  data IOException" + e);
        }
    }

    private void startDevFbCheck() {
        if (zigbeeInit == SERVICE_MACHINE_NORMAL) {
            devCtlTimeOutFlag = 1;
            mdevFbcnt = 0;
            mdevFbDelay = 0;
            msgRemove(SERVICE_MSG_TICK_READLIST);
            sendHandleMsg(SERVICE_MSG_TICK_READLIST, 1000 * SERVICE_READ_DEV_LIST_TIME_1S);
        }
    }

    private void stopDevFbCheck() {
        devCtlTimeOutFlag = 0;
        mdevFbcnt = 0;
    }

    private int getDevFbCheck() {
        return devCtlTimeOutFlag;
    }

    /**
     * 更新HCP配置(重新生成数据库）
     * @param hcp
     */
    private void updateHcp(HcpFile hcp) {
        Log.e(TAG, "!!Device DB reset!! (HCP reset)");

        String zKey;
        stopDevFbCheck();
        zKey = hcp.boxInfo.getZkey();
        if (zKey != null)
            mDeviceManager.securityKey(null, hcp.boxInfo.getZkey().getBytes());
        else {
            Log.e(TAG, "!!zkey invaild!! (HCP reset)");
        }
        mDeviceDbManager.reset();
        for (int i = 0; i < hcp.devices.size(); i++) {
            DeviceDb dev = hcp.devices.get(i);
            mDeviceDbManager.add(
                    dev.getBoxId(),
                    dev.getNetType(),
                    dev.getType(),
                    dev.getGwDevId(),
                    dev.getDevId(),
                    dev.getMacAddr(),
                    dev.getName(),
                    dev.getBindSw1(),
                    dev.getBindSw2(),
                    dev.getRegionId(),
                    dev.getDevCfg()
            );
        }

        KnxDeviceDao daoKnx = new KnxDeviceDao(this);
        daoKnx.deleteAll();
        for (int i = 0; i < hcp.knxDevices.size(); i++)
            daoKnx.add(hcp.knxDevices.get(i));

        SceneDao dao = new SceneDao(this);
        dao.deleteAll();
        for (int i = 0; i < hcp.scenes.size(); i++)
            dao.add(hcp.scenes.get(i));

        SceneDeviceDao dao2 = new SceneDeviceDao(this);
        dao2.deleteAll();
        for (int i = 0; i < hcp.sceneDevs.size(); i++)
            dao2.add(hcp.sceneDevs.get(i));

        NavigationDao dao3 = new NavigationDao(this);
        dao3.deleteAll();
        for (int i = 0; i < hcp.navis.size(); i++)
            dao3.add(hcp.navis.get(i));

        BoxInfoDao daoBox = new BoxInfoDao(this);
        daoBox.deleteAll();
        daoBox.add(hcp.boxInfo);

        ProjectDao prjBox = new ProjectDao(this);
        prjBox.deleteAll();
        prjBox.add(hcp.projInfo);

        ServiceInfoDao serviceBox = new ServiceInfoDao(this);
        serviceBox.deleteAll();

        VoiceConfigDao daoVoice = new VoiceConfigDao(this);
        daoVoice.deleteAll();
        daoVoice.initLightData();

        for (int i = 0; i < hcp.services.size(); i++) {
            serviceBox.add(hcp.services.get(i));
        }
        //发送广播，告知上层
        Intent intentUpdate = new Intent(CommonIntent.ACTION_HCP_UPDATED);
        mContext.sendBroadcast(intentUpdate);
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context myContext, Intent myntent) {
            final Intent intent = myntent;
            final Context context = myContext;
            // TODO Auto-generated method stub       	
            singleThreadExecutorReceive.execute(new Runnable() {
                @Override
                public void run() {
                    if (intent.getAction().startsWith(CommonIntent.ACTION_DEV_MANAGER, 0)) {
                        //设备管理
                        intentManageCmdProc(intent);
                    } else if (intent.getAction().startsWith(CommonIntent.ACTION_DEV_CTL, 0)) {
                        //设备控制时
                        try {
                            Log.d(TAG, "!!! ACTION_DEV_CTL put !!!");
                            //控制指令加入队列
                            SerialDataUnpack.getSingleInstance(context).intentQueue.put(intent);

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else if (intent.getAction().equals(CommonIntent.ACTION_TEST_DEV_STATUS)) {
                        //设备状态
                        mDeviceManager.DbCheckStatus(1);
                    } else if (intent.getAction().equals(CommonIntent.ACTION_GATEWAY_FACTORY_MODE)) {//GateWay factory mode
                        intentRsp(CommonIntent.ACTION_GATEWAY_FACTORY_MODE, 0);
                    } else if (intent.getAction().equals(CommonIntent.ACTION_BOX_RENAME)) {
                        //修改终端名称
                        if (debug) Log.d(TAG, "ACTION_BOX_RENAME");
                        try {
                            String deviceId = intent.getStringExtra("deviceId");
                            String newName = intent.getStringExtra("newName");
                            DbManager db = CommonUtil.MyDbUtils();
                            try {
                                DeviceDb me = db.selector(DeviceDb.class).where("devId", "=", deviceId).findFirst();
                                if (me != null) {
                                    intentRsp(CommonIntent.ACTION_BOX_RENAME, 0);
                                    me.setName(newName);
                                } else {
                                    Log.d(TAG, "Box rename: Not found, devId:" + deviceId);
                                }
                            } catch (DbException | NumberFormatException e) {
                                intentRsp(CommonIntent.ACTION_BOX_RENAME, 1);
                                e.printStackTrace();

                            }
                        } catch (Exception e) {
                            intentRsp(CommonIntent.ACTION_BOX_RENAME, 1);
                            Log.e(TAG, "Error:" + e);
                        }
                    } else if (intent.getAction().equals(CommonIntent.ACTION_HCP_RESET)) {
                        //重置HCP
                        int devHcp = intent.getIntExtra("devHcp", 0);
                        msgRemove(SERVICE_MSG_Zigbee_Reset);
                        msgRemove(SERVICE_MSG_ADD_DEV);
                        sendHandleMsg(SERVICE_MSG_UPDATA_HCP, devHcp, 1000);
                        Log.d(TAG, "This devHcp:" + devHcp);
                    } else if (intent.getAction().equals(CommonIntent.ACTION_BOX_WIREDNET_TO_ZIGBEE)) {
                        //有线网转ZigBee
                        Log.e(TAG,"====ACTION_BOX_WIREDNET_TO_ZIGBEE=====");

                        byte[] wirdtozigbeeData = intent.getByteArrayExtra("wirdtozigbeeData");
                        if (wirdtozigbeeData.length > 3) {
                            byte[] unpackData = CommonUtil.getSpecbyte(wirdtozigbeeData, 2, wirdtozigbeeData.length - 3);

                            sendHandleMsg(ZigBeeDataProcess.UNPACK_RX_DATA, unpackData);
                            Log.d(TAG, "FB data:" + CommonUtil.bytesToHexString(wirdtozigbeeData, wirdtozigbeeData.length));
                            Log.d(TAG, "FB unpack data:" + CommonUtil.bytesToHexString(unpackData, unpackData.length));
                        } else {
                            Log.d(TAG, "FB data error");
                        }
                    }
                }
            });
        }
    };

    /**
     * 处理管理指令（设备管理相关)
     * @param intent
     */
    public void intentManageCmdProc(Intent intent) {
        String boxId = intent.getStringExtra("boxId");
        int regionId = intent.getIntExtra("regionId", 0);
        int type = intent.getIntExtra("type", 0);
        int netTpye = intent.getIntExtra("network", 0);
        String deviceId = intent.getStringExtra("deviceId");
        String mac = intent.getStringExtra("macAddr");
        String name = intent.getStringExtra("name");
        String bindSw1 = intent.getStringExtra("bindSw1");
        String bindSw2 = intent.getStringExtra("bindSw2");
        if (netTpye != DeviceManager.ZIGBEE_NETWORK) {
            return;
        }
        Log.d(TAG, "ZigBee Service Manager:" + intent.getAction());

        switch (intent.getAction()) {
            case CommonIntent.ACTION_DEV_ADD:
                if (!CommonUtil.checkMacFormat(mac)) {
                    return;
                }
                if (debug) Log.d(TAG, "ACTION_DEV_ADD,ZigBee");
                mDeviceManager.add(null, mac, deviceId);
                mDeviceDbManager.add(boxId, netTpye, type, "", deviceId, mac, name, bindSw1, bindSw2, regionId, "");

                break;
            case CommonIntent.ACTION_DEV_REMOVE:
                mDeviceDbManager.del(mac);
                mDeviceManager.remove(null, mac);
                if (debug) Log.d(TAG, "ACTION_DEV_REMOVE");break;

            case CommonIntent.ACTION_DEV_ONOFFLINE:
                if (debug) Log.d(TAG, "Action Dev Status");
                intentRsp(CommonIntent.ACTION_DEV_ONOFFLINE, 0);
                mDeviceManager.status(null, mac);
                break;
            case CommonIntent.ACTION_DEV_BIND: {
                String bindMac = intent.getStringExtra("bindDevid");
                int group = intent.getIntExtra("group", 0);
                Log.d(TAG, "ACTION_DEV_BIND success :" + "mac:" + mac + "BindMac:" + bindMac);
                mDeviceManager.getPanID();
                mDeviceManager.allLightOn();
                mDeviceManager.getMyDevOnlineNum();
                mDeviceManager.getAssoclistNum();
                mDeviceManager.getGwError();
                Log.d(TAG, "!!!!!getPanID!!!!!");

                if (!CommonUtil.checkMacFormat(mac)) {
                    Log.e(TAG, "ACTION_DEV_BIND mac error :");
                    return;
                }
                mDeviceManager.bind(null, mac, bindMac, group, 1);
                mDeviceDbManager.bind(mac, bindMac, group);
                intentRsp(CommonIntent.ACTION_DEV_BIND, 0);
                break;
            }
            case CommonIntent.ACTION_DEV_UNBIND: {
                int group = intent.getIntExtra("group", 0);
                Log.d(TAG, "group=" + group);

                if (group == 2) {
                    mDeviceManager.ManualZigBeeGwClearAssoclist();
                } else if(group == 0) {
                    mDeviceManager.ManualResetAssoclist();
                }
                else if (10 < group && group <26)
                {
                    int temp = 26 - group;
                    String s_key = "CN10000000000000" + temp;
                    Log.d(TAG, "set key:" + s_key);
                    mDeviceManager.securityKey(null, s_key.getBytes());
                }

                intentRsp(CommonIntent.ACTION_DEV_UNBIND, 0);
                break;
            }
            case CommonIntent.ACTION_DEV_SECURITYKEY:
                String key = intent.getStringExtra("key");
                Log.d(TAG, "ACTION_DEV_SecurityKey success :" + "key:" + key);

                if (!CommonUtil.checkMacFormat(key)) {
                    Log.e(TAG, "ACTION_DEV_SecurityKey key length error :");
                    return;
                }
                mDeviceManager.securityKey(null, key.getBytes());
                intentRsp(CommonIntent.ACTION_DEV_SECURITYKEY, 0);
                break;
            case CommonIntent.ACTION_DEV_CLEARLIST:
                int clearlist = intent.getIntExtra("clearlist", 0);
                if (clearlist == 5555) {
                    intentRsp(CommonIntent.ACTION_DEV_CLEARLIST, 0);
                    mDeviceManager.clearList();
                    Log.e(TAG, "ACTION_DEV_CLEARLIST success :");
                } else {
                    intentRsp(CommonIntent.ACTION_DEV_CLEARLIST, 1);
                    Log.e(TAG, "Error:");
                }
                break;
            case CommonIntent.ACTION_DEV_MANUALCLEARZIGBEEGWASSOCLIST:
                intentRsp(CommonIntent.ACTION_DEV_MANUALCLEARZIGBEEGWASSOCLIST, 0);
                mDeviceManager.ManualZigBeeGwClearAssoclist();
                Log.d(TAG, "ACTION_DEV_MANUALCLEARZIGBEEGWASSOCLIST success :");
                break;
        }
        Log.e(TAG, "reutrn success :");
    }

    public void intentRsp(String intent, int result) {
        Intent mIntent = new Intent(CommonIntent.ACTION_INFO_RETURN);
        mIntent.putExtra("intentId", intent);
        mIntent.putExtra("return", result);
        mContext.sendBroadcast(mIntent);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public void onDestroy() {
        super.onDestroy();
        msgHandlethread.stopThread();
        mZigBeeDataProcess.stopDataProcess();
        singleThreadExecutorReceive.shutdown();
        unregisterReceiver(mReceiver);
        CommonUtil.MyDbUtilsClose();
    }
}
